const {src, dest, parallel, series, watch}  = require("gulp")
const less = require('gulp-less');
const cleanCSS  = require("gulp-clean-css")
const rename = require("gulp-rename")
const prefixer = require("gulp-autoprefixer")
const del = require("del")
const babel = require('gulp-babel');
const uglify = require("gulp-uglify")
const htmlmin = require("gulp-htmlmin")
const imagemin = require("gulp-imagemin")
const browserSync = require("browser-sync")
const bs = browserSync.create()

const style = () => {
  return src("src/styles/main.less", {base: 'src'})
  .pipe(less())
  .pipe(prefixer())
  // .pipe(cleanCSS())
  // .pipe(rename({
  //   "extname": ".min.css"
  // }))
  .pipe(dest("dist"))
}



// 声明脚本构建任务
const script = () => {
  return src("src/js/main.js", {base: 'src'})
  .pipe(uglify())
  .pipe(rename({
      "extname": ".min.js"
    }))
  // .pipe(babel({
  //   // presets: ['@babel/env'] // babel7的写法
  //   presets: ['babel-preset-env']  //babel6的写法
  // })) 
  .pipe(dest('dist')) 
} 

const html = () => {
  return src("src/index.html", {base: 'src'})
  .pipe(htmlmin({
     collapseWhitespace: true ,
     minifyCSS: true,
     minifyJS: true
    }))
  .pipe(dest('dist'))  
}



const image = () => {
  return src("src/img/**")
  .pipe(imagemin([
    imagemin.mozjpeg({quality: 75, progressive: true})
  ]))
  .pipe(dest('dist'))  
}

const clean = () => {
  return del(["dist"])
}

const serve = () => {
  // watch 被监视的文件，执行对应的任务
  watch('src/index.html', html)
  watch('src/styles/*.less', style)
  watch('src/js/*.js', script)
  watch('src/img/**', image)
  
  bs.init({
    notify: false,  //禁用浏览器右上角的 browserSync
    files: 'dist/**',  // 监视dist下文件的变化
    server: {
      baseDir: './dist',  //指定服务启动的目录
      routes:{
        "/node_modules": 'node_modules' 
      }
    },
  })
}

const build = parallel(style, script, html)

const dev = series(clean, build)

module.exports = {
  style, script, html, build, image, clean, dev, serve
}